﻿using Newtonsoft.Json.Linq;
using QD.UpDownLoad;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QD.LopPlat.UI.Code
{
    /// <summary>
    /// RichTextBox内容压缩和解压类
    /// </summary>
    public class RtfHelper
    {
        //压缩
        public static byte[] GetRichTextBoxData(RichTextBox txt)
        {
            byte[] bs = null;
            using (MemoryStream ms = new MemoryStream())
            {
                txt.SaveFile(ms, RichTextBoxStreamType.RichText);
                bs = ms.ToArray();
            }
            using (MemoryStream ms = new MemoryStream())
            {
                using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
                {
                    ZipArchiveEntry readMeEntry = archive.CreateEntry("doc");
                    using (Stream s = readMeEntry.Open())
                    {
                        s.Write(bs, 0, bs.Length);
                    }
                }
                if (ms.Length > 1048576)
                {
                    throw new Exception("内容大于1M请缩减内容后再保存！");
                }
                return ms.ToArray();
            }
        }

        //解压缩
        public static void LoadRichTextBoxData(RichTextBox txt, byte[] data)
        {
            byte[] bs = null;
            using (MemoryStream ms = new MemoryStream(data))
            {
                using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Read))
                {
                    ZipArchiveEntry entry = archive.GetEntry("doc");
                    using (MemoryStream ms2 = new MemoryStream())
                    {
                        int b = -1;
                        using (var s = entry.Open())
                        {
                            while ((b = s.ReadByte()) != -1)
                            {
                                ms2.WriteByte((byte)b);
                            }
                        }
                        bs = ms2.ToArray();
                    }
                }
            }
            using (MemoryStream newData = new MemoryStream(bs))
            {
                txt.LoadFile(newData, RichTextBoxStreamType.RichText);
            }
        }
        /// <summary>
        /// 下载RichTextBox Rtf文件
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="Path"></param>
        /// <returns></returns>
        public static byte[] DownloadFiles(string FilePath)
        {
            System.Net.WebClient myWebClient = new System.Net.WebClient();
            if (string.IsNullOrEmpty(WebClientHelper.ServerUri))
            {
                throw new Exception("未设置服务器的URL");
            }
            Uri _uri = new Uri(WebClientHelper.ServerUri + FilePath);
            byte[] b = myWebClient.DownloadData(_uri);
            return b;
        }
        /// <summary>
        /// 上传RichTextBox Rtf文件到服务器
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public static string UploadFile(Byte[] b, string path)
        {
            //年月文件夹
            string UploadFile = "/" + DateTime.Now.ToString("yyyyMM") + "/";
            //文件名
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".rtf";
            //服务器上传地址
            string url = WebClientHelper.ServerUri;
            if (string.IsNullOrEmpty(WebClientHelper.ServerUri) || string.IsNullOrEmpty(path))
            {
                throw new Exception("服务器地址或者存储路径未设置！");
            }
            //服务器文件地址
            string serverFile = path + UploadFile;
            //本地文件保存路径
            string localFile = Application.StartupPath + "/UploadFile" + UploadFile;
            //创建临时文件夹
            if (!System.IO.Directory.Exists(localFile))  //如果不存在路径
            {
                System.IO.Directory.CreateDirectory(localFile);     //创建路径
            }
            //把文件保存在本地
            ByteHelper.WriteByteToFile(b, localFile + fileName);
            //把本地文件上传到服务器
            UpLoadFile(localFile + fileName, "E:/QDBUGReqsFile" + serverFile, url);

            string FilePath = "/QDBUGReqsFile" + serverFile + fileName;
            return FilePath;
        }
        private static void UpLoadFile(string filePath, string UploadFile, string url)
        {
            System.Net.WebClient myWebClient = new System.Net.WebClient();
            //上传的链接地址（文件服务器）
            Uri _uri = new Uri(url + "/api/FileUpload/PostUpload?UploadFile=" + UploadFile);
            //上传文件到服务器
            byte[] b = myWebClient.UploadFile(_uri, "POST", filePath);
            //string strJson = System.Text.Encoding.Default.GetString(b);
            //JObject jObj = JObject.Parse(strJson);
            //if (jObj["success"].ToString() == "False")
            //{
            //    new Exception(jObj["error"].ToString());
            //}
        }
    }
}
